package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.service.TokenService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.module.estate.Estate;
import com.ruoyi.system.domain.module.estate.EstateUser;
import com.ruoyi.system.domain.module.mer.MerUser;
import com.ruoyi.system.domain.module.wx.UserMp;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.domain.system.SysPost;
import com.ruoyi.system.domain.system.SysUserRole;
import com.ruoyi.system.service.module.attendance.IAttendanceGroupService;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.estate.IEstateUserService;
import com.ruoyi.system.service.module.mer.IMerUserService;
import com.ruoyi.system.service.module.property.IPropertyUserService;
import com.ruoyi.system.service.module.wx.IUserMpService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysPostService;
import com.ruoyi.system.service.system.ISysRoleService;
import com.ruoyi.system.service.system.ISysUserRoleService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.web.controller.common.BaseController;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Validated
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
	private final ISysUserService userService;
	private final ISysRoleService roleService;
	private final ISysPostService postService;
	private final TokenService tokenService;
	private final IEstateService estateService;
    private final IWxUserService wxUserService;
	private final IMerUserService merUserService;
	private final IUserMpService userMpService;
	private final ISysUserRoleService sysUserRoleService;
    private final IEstateUserService estateUserService;
    private final IPropertyUserService propertyUserService;
    private final IAttendanceGroupService attendanceGroupService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:list,module:meruser:list')")
    @GetMapping("/list")
    public TableDataInfo<SysUser> list(SysUser user) {
        QueryWrapper<SysUser> qw1 =new QueryWrapper<>();
        if (user.getUserId()!=null){
            qw1.eq("user_id",user.getUserId());
        }
        if(user.getDutyGroupId()!=null){
            qw1.eq("duty_group_id",user.getDutyGroupId());
        }
        if(user.getUserType()!=null){
            qw1.eq("user_type",user.getUserType());
        }
        if(user.getNickName()!=null){
            qw1.like("nick_name",user.getNickName());
        }
        if (user.getPropertyId()!=null){
            qw1.eq("property_id",user.getPropertyId());
        }
		if (user.getEstateId()!=null){
			qw1.eq("estate_id",user.getEstateId());
		}
		if (user.getPhoneNum()!=null){
			qw1.eq("phone_num",user.getPhoneNum());
		}
        TableDataInfo<SysUser> dt = PageUtils.buildDataInfo(userService.page(PageUtils.buildPage(), qw1));
        /*TableDataInfo<SysUser> dt = userService.selectPageUserList(user);*/
        List<SysUser> list = dt.getRows();
        if(CollUtil.isNotEmpty(list)){
            for(SysUser sysUser : list){
                String nickName = "";
                QueryWrapper<EstateUser> qw = new QueryWrapper<>();
				if (user.getEstateId()!=null){
					qw.eq("estate_id",user.getEstateId());
				}
                qw.eq("sys_user_id",sysUser.getUserId());
                List<EstateUser> estateUserList = estateUserService.list(qw);
                if(CollUtil.isNotEmpty(estateUserList)){
                    for (EstateUser estateUser : estateUserList){
                        WxUser wxUser = wxUserService.findById(estateUser.getUserId());
                        if(wxUser!=null){
                            nickName += EmojiParser.parseToUnicode(wxUser.getNickName()) + ",";
                        }
                    }
                    if(nickName.length() > 0){
                        nickName = nickName.substring(0,nickName.length() -1);
                    }
                }
                sysUser.setWxNickName(nickName);
            }
        }
        return dt;
    }

	@PreAuthorize("@ss.hasAnyPermi('system:user:list,module:meruser:list')")
	@GetMapping("/lists")
	public AjaxResult lists(SysUser user) {
		SysUser sysUser = getUser();
		QueryWrapper<SysUser> qw1 =new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw1.eq("property_id",sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			qw1.eq("estate_id",sysUser.getEstateId());
		}else{
			if(user.getPropertyId() != null){
				qw1.eq("property_id",user.getPropertyId());
			}
			if(user.getEstateId() != null){
				qw1.eq("estate_id",user.getEstateId());
			}
		}
		TableDataInfo<SysUser> dt = PageUtils.buildDataInfo(userService.page(PageUtils.buildPage(), qw1));
		/*TableDataInfo<SysUser> dt = userService.selectPageUserList(user);*/
		List<SysUser> list = dt.getRows();
		return AjaxResult.success(list);
	}

	/**
	 * 获取用户列表
	 */
	@PreAuthorize("@ss.hasAnyPermi('system:user:list,module:meruser:list')")
	@GetMapping("/listByMer")
	public TableDataInfo<SysUser> listByMer(SysUser user) {
		TableDataInfo<SysUser> dt = userService.selectPageMerUserList(user);
		List<SysUser> list = dt.getRows();
		if(CollUtil.isNotEmpty(list)){
			for(SysUser sysUser : list){
				String nickName = "";

				QueryWrapper<MerUser> qw = new QueryWrapper<>();
				if (user.getMerId()!=null){
					qw.eq("mer_id",user.getMerId());
				}
				if (user.getUserId()!=null){
					qw.eq("sys_user_id",sysUser.getUserId());
				}
				if (user.getDeptId()!=null){
					qw.eq("dept_id",user.getDeptId());
				}
				List<MerUser> merUsers = merUserService.list(qw);
				if(CollUtil.isNotEmpty(merUsers)){
					for (MerUser merUser : merUsers){
						WxUser wxUser = wxUserService.findById(merUser.getUserId());
						if(wxUser!=null){
							QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
							qwMp.eq("union_id",wxUser.getUnionId());
							qwMp.last("limit 1");
							UserMp userMp = userMpService.getOne(qwMp);
							if(userMp != null){
								nickName += EmojiParser.parseToUnicode(wxUser.getNickName()) +"(已关注公众号)" + ",";
							}else{
								nickName += EmojiParser.parseToUnicode(wxUser.getNickName())+"(未关注公众号)"  + ",";
							}
						}
					}
					if(nickName.length() > 0){
						nickName = nickName.substring(0,nickName.length() -1);
					}
				}
				sysUser.setWxNickName(nickName);
			}
		}
		return dt;
	}


	/**
	 * 获取用户列表
	 */
	@PreAuthorize("@ss.hasAnyPermi('system:user:list,module:estateUser:list')")
	@GetMapping("/listByEstate")
	public TableDataInfo<SysUser> listByEstate(SysUser user) {
		TableDataInfo<SysUser> dt = userService.selectPageEstateUserList(user);
		List<SysUser> list = dt.getRows();
		if(CollUtil.isNotEmpty(list)){
			for(SysUser sysUser : list){
				String nickName = "";
				QueryWrapper<EstateUser> qw = new QueryWrapper<>();
				if (user.getMerId()!=null){
					qw.eq("mer_id",user.getMerId());
				}
				if (user.getUserId()!=null){
					qw.eq("sys_user_id",sysUser.getUserId());
				}
				if (user.getDeptId()!=null){
					qw.eq("dept_id",user.getDeptId());
				}
				List<EstateUser> estateUserList = estateUserService.list(qw);
				if(CollUtil.isNotEmpty(estateUserList)){
					for (EstateUser estateUser : estateUserList){
						WxUser wxUser = wxUserService.findById(estateUser.getUserId());
						if(wxUser!=null){
							nickName += EmojiParser.parseToUnicode(wxUser.getNickName()) + ",";
						}
					}
					if(nickName.length() > 0){
						nickName = nickName.substring(0,nickName.length() -1);
					}
				}
				sysUser.setWxNickName(nickName);
			}
		}
		return dt;
	}


	@Log(title = "用户管理")
	@GetMapping("/listByUserType")
	public AjaxResult listByUserType(SysUser user)
	{
		List<SysUser> list = userService.selectUserList(user);
		return AjaxResult.success(list);
	}


	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasAnyPermi('system:user:export,module:meruser:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasAnyPermi('system:user:import,module:meruser:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:query,module:meruser:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
		SysPost post = new SysPost();
		SysUser sysUser = getUser();
		if(sysUser.getUserType() < 2){
			post.setPropertyId(0);
			post.setEstateId(0);
		} else if(sysUser.getUserType() == 2){
			post.setPropertyId(sysUser.getPropertyId());
		} else if(sysUser.getUserType() == 3){
			post.setEstateId(sysUser.getEstateId());
		}else{
			post.setPropertyId(0);
			post.setEstateId(0);
		}

        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll(post));
        if (Validator.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return AjaxResult.success(ajax);
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:add,module:meruser:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (Validator.isNotEmpty(user.getPhoneNum())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        if(user.getRoleIds() != null && user.getRoleIds().length > 0){
        	SysRole sysRole = roleService.getById(user.getRoleIds()[0]);
        	if(sysRole!=null){
				user.setUserType(sysRole.getUserType());

				if(sysRole.getUserType() == 2){//物业管理员

                } else if(sysRole.getUserType() == 3){//小区管理员
                    Estate estate = estateService.findById(user.getEstateId());
                    if(estate!=null){
                        user.setPropertyId(estate.getPropertyId());
                    }
                    user.setMerId(0);
                } else if(sysRole.getUserType() == 4){//商家管理员
                    user.setPropertyId(0);
                    user.setEstateId(0);
                }
			}
			user.setRoleId(user.getRoleIds()[0]);
		}else{
			SysRole sysRole = roleService.getById(user.getRoleId());
			if(sysRole!=null){
				user.setUserType(sysRole.getUserType());
				if(sysRole.getUserType() == 2){//物业管理员

				} else if(sysRole.getUserType() == 3){//小区管理员
					Estate estate = estateService.findById(user.getEstateId());
					if(estate!=null){
						user.setPropertyId(estate.getPropertyId());
					}
					user.setMerId(0);
				} else if(sysRole.getUserType() == 4){//商家管理员
					user.setPropertyId(0);
					user.setEstateId(0);
				}
			}
		}

		Integer[] posts = user.getPostIds();
		if(posts != null && posts.length > 0){
			user.setPostId(posts[0]);
		}

		int ret = userService.insertUser(user);
        if(ret > 0){
			if(user.getUserType() == 4){//商家管理员
				QueryWrapper<MerUser> qw = new QueryWrapper<>();
				qw.eq("sys_user_id",user.getUserId());
				qw.last("limit  1");
				MerUser merUser = merUserService.getOne(qw);
				if(merUser == null){
					merUser = new MerUser();
					merUser.setSysUserId(user.getUserId());
					merUser.setUserType(0);
					merUser.setIsAdmin(0);
					merUser.setMerId(user.getMerId());
					merUser.setCreateTime(new Date());
					merUserService.save(merUser);
				}
			}else if(user.getUserType() == 3){
				QueryWrapper<EstateUser> qwManger = new QueryWrapper<>();
				qwManger.eq("estate_id",user.getEstateId());
				qwManger.eq("is_manager", 1);
				qwManger.last("limit  1");
				EstateUser estateUserManager = estateUserService.getOne(qwManger);

				QueryWrapper<EstateUser> qw = new QueryWrapper<>();
				qw.eq("sys_user_id",user.getUserId());
				qw.last("limit  1");
				EstateUser estateUser = estateUserService.getOne(qw);
				if(estateUser == null){
					estateUser = new EstateUser();
					estateUser.setSysUserId(user.getUserId());
					estateUser.setUserType(0);
					if(estateUserManager!=null){
						estateUser.setIsManager(0);
					}else{
						estateUser.setIsManager(1);
					}
					estateUser.setState(1);
					estateUser.setEstateId(user.getEstateId());
					estateUser.setCreateTime(new Date());
					estateUserService.save(estateUser);
				}
			}
		}
        return toAjax(ret);
    }

	/**
	 * 添加用户账户
	 */
	@PreAuthorize("@ss.hasAnyPermi('system:user:edit,module:meruser:edit')")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PutMapping("/updateSysUser/{userIds}")
	public AjaxResult updateSysUser(@PathVariable Integer userIds) {
		EstateUser estateUser = estateUserService.findById(userIds);
		SysUser user = userService.selectUserById(estateUser.getSysUserId());
		user.setUserType(3);
		user.setRoleId(3);
		SysUserRole role = new SysUserRole();
		role.setRoleId(3);
		role.setUserId(user.getUserId());
		QueryWrapper<SysUserRole> qw = new QueryWrapper<>();
		qw.eq("user_id",user.getUserId());
		sysUserRoleService.remove(qw);
		Boolean b = false;
		b = sysUserRoleService.save(role);
		if (b){
			return toAjax(userService.updateById(user)?1:0);
		}else {
			return toAjax(0);
		}

	}

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:edit,module:meruser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (Validator.isNotEmpty(user.getPhoneNum())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (Validator.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
		if(user.getRoleIds()!=null && user.getRoleIds().length > 0){
			SysRole sysRole = roleService.getById(user.getRoleIds()[0]);
			if(sysRole!=null){
				user.setUserType(sysRole.getUserType());
                if(sysRole.getUserType() == 2){//物业管理员

                } else if(sysRole.getUserType() == 3){//小区管理员
                    Estate estate = estateService.findById(user.getEstateId());
                    if(estate!=null){
                        user.setPropertyId(estate.getPropertyId());
                    }
                    user.setMerId(0);
                } else if(sysRole.getUserType() == 4){//商家管理员
                    user.setPropertyId(0);
                    user.setEstateId(0);
                }
			}
			user.setRoleId(user.getRoleIds()[0]);
		}
		Integer[] posts = user.getPostIds();
		if(posts!=null && posts.length > 0){
			user.setPostId(posts[0]);
		}
        int ret = userService.updateUser(user);
        if(ret > 0){
            if(user.getUserType() == 4){//商家管理员
                QueryWrapper<MerUser> qw = new QueryWrapper<>();
                qw.eq("sys_user_id",user.getUserId());
                qw.last("limit  1");
                MerUser merUser = merUserService.getOne(qw);
                if(merUser == null){
                    merUser = new MerUser();
                    merUser.setSysUserId(user.getUserId());
                    merUser.setUserId(0);
                    merUser.setUserType(0);
                    merUser.setIsAdmin(0);
                    merUser.setMerId(user.getMerId());
                    merUser.setCreateTime(new Date());
                    merUserService.save(merUser);
                }
            }else if(user.getUserType() == 3){
                QueryWrapper<EstateUser> qwManger = new QueryWrapper<>();
                qwManger.eq("estate_id",user.getEstateId());
                qwManger.eq("is_manager", 1);
                qwManger.last("limit  1");
                EstateUser estateUserManager = estateUserService.getOne(qwManger);

                QueryWrapper<EstateUser> qw = new QueryWrapper<>();
                qw.eq("sys_user_id",user.getUserId());
                qw.last("limit  1");
                EstateUser estateUser = estateUserService.getOne(qw);
                if(estateUser == null){
                    estateUser = new EstateUser();
                    estateUser.setSysUserId(user.getUserId());
                    estateUser.setUserId(0);
                    estateUser.setUserType(0);
                    if(estateUserManager!=null){
                        estateUser.setIsManager(0);
                    }else{
                        estateUser.setIsManager(1);
                    }
					estateUser.setState(1);
                    estateUser.setEstateId(user.getEstateId());
                    estateUser.setCreateTime(new Date());
                    estateUserService.save(estateUser);
                }
            }
        }
        return toAjax(ret);
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:remove,module:meruser:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:resetPwd,module:meruser:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:edit,module:meruser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:query,module:meruser:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
		Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return AjaxResult.success(ajax);
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:edit,module:meruser:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Integer[] roleIds)

    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
    @GetMapping("/group/{id}")
    public Integer getGroup(@PathVariable("id") Integer id){
        QueryWrapper<SysUser> qw=new QueryWrapper<>();
        qw.eq("user_id",id);
        List<SysUser> sysUsers = userService.list(qw);
        Integer dutyGroupId=0;
        for (SysUser sysUser:sysUsers){
            dutyGroupId = sysUser.getDutyGroupId();
        }
        return dutyGroupId;
    }





}
